<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="queryParams.name" clearable placeholder="请输入内容" class="search-main" @input="onSearch" />
      <el-button type="primary">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-auth-btn="'park:enterprise.add_edit'" type="primary" @click="$router.push('/park/add')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="enterpriseList">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime">
                <el-table-column label="合同状态" prop="status">
                  <template #default="{row}">
                    <el-tag :type="formatInfoType(row.status)">
                      {{ formatStatus(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                  <template #default="{row}">
                    <el-button size="mini" type="text">续租</el-button>
                    <el-button size="mini" :disabled="row.status===3" type="text" @click="outRent(row.id)">退租</el-button>
                    <el-button size="mini" :disabled="[0,1,2].includes(row.status)" type="text">删除</el-button>
                  </template>
                </el-table-column>
              </el-table-column></el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="addRent(row.id)">添加合同</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/park/info/${row.id}`)">查看</el-button>
            <el-button size="mini" type="text" @click="$router.push(`/park/add/${row.id}`)">编辑</el-button>
            <el-button size="mini" type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="queryParams.pageSize"
        @current-change="pageChange"
      />
    </div>
    <el-dialog
      title="提示"
      :visible="rentShowDialog"
      width="580px"
      :before-close="handleClose"
    >
      <span>添加合同</span>
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="rentRef" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="uploadref"
              action="#"
              :http-request="uploadRequest"
              :before-upload="beforeUpload"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" @change="$refs.uploadRef.click()">上传合同文件</el-button>
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addRentAPI, delEnterpriseAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI, uploadAPI } from '@/api/enterprise'
import { Message } from 'element-ui'

export default {
  name: 'Park',
  data() {
    return {
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业名称
        type: 0, // 合同类型
        rentTime: [] // 合同时间
      },
      fileList: [],
      rentList: [],
      enterpriseList: [],
      queryParams: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      total: 0,
      rentShowDialog: false,
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' },
          { validator: (rule, value, callback) => {
            if (new Date(value[0]) > new Date(value[1])) {
              callback(new Error('租赁开始日期不能早于租赁结束日期'))
            } else {
              return
            }
          }, trigger: 'blur' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      }
    }
  },
  created() {
    this.getEnterprise()
  },
  methods: {
    outRent(id) {
      this.$confirm('确定要退租吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(id)
        Message.success('退租成功')
        this.getEnterprise()
      }).catch(() => {
        Message.info('已取消退租')
      })
    },
    formatInfoType(status) {
      const MAP = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return MAP[status]
    },
    formatStatus(type) {
      const TYPEMAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return TYPEMAP[type]
    },
    async uploadRequest(data) {
      const file = data.file
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'contract')
      const res = await uploadAPI(formData)
      this.rentForm.contractId = res.id
      this.rentForm.contractUrl = res.url
      this.fileList.push({
        name: res.id,
        url: res.url
      })
      this.$refs.rentRef.validateField('contractId')
    },
    beforeUpload(file) {
      const allowImgType = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        Message.error('上传合同文件只能是 .doc, .pdf 格式!')
        return
      }
      if (!isLt5M) {
        Message.error('上传合同文件大小不能超过 5MB!')
        return
      }
      return allowImgType && isLt5M
    },
    async confirm() {
      try {
        // await this.$refs.rentRef.validate()
        const { buildingId, contractId, contractUrl, enterpriseId, type } = this.rentForm
        await addRentAPI({ startTime: this.rentForm.rentTime[0], endTime: this.rentForm.rentTime[1], buildingId, contractId, contractUrl, enterpriseId, type })
        Message.success('添加成功')
        this.getEnterprise()
        this.cancel()
      } catch (error) {
        Message.error(error)
      }
    },
    async addRent(id) {
      this.rentShowDialog = true
      this.rentForm.enterpriseId = id
      // 添加
      const res = await getRentBuildListAPI()
      this.rentList = res
    },
    handleClose() {
      this.cancel()
    },
    cancel() {
      this.rentShowDialog = false
      this.$refs.rentRef.resetFields()
      this.rentForm.contractUrl = ''
      this.rentForm.contractId = ''
      this.contractList = []
    },
    del(id) {
      this.$confirm('确定要删除该企业吗', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delEnterpriseAPI(id)
        Message.success('删除成功')
        this.getEnterprise()
      })
    },
    onSearch() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getEnterprise()
      })
    },
    async getEnterprise() {
      const { rows, total } = await getEnterpriseListAPI(this.queryParams)
      this.enterpriseList = rows
      this.total = total
      this.enterpriseList.forEach(async item => {
        this.$set(item, 'rentList', await getRentListAPI(item.id))
      })
    },
    async pageChange(val) {
      console.log(val)
      this.queryParams.page = val
      await this.getEnterprise()
    }
  }
}
</script>
<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
